package com.sweet.auth;

import com.sweet.enums.Charset;
import com.sweet.json.JsonUtil;
import com.sweet.util.WebUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求信息认证
 *
 * @author limi
 * @create 2019-04-08-14:01
 */
@Slf4j
public final class RequestAuth {
    /**
     * 认证失败状态码
     */
    private static final int AUTH_FAILURE_CODE = 400;

    private RequestAuth() {
    }

    /**
     * 返回认证失败信息
     *
     * @param request  请求
     * @param response 响应
     * @param ip       来访ip
     * @param message  反馈信息
     * @param printLog 是否打印日志
     */
    public static void fail(HttpServletRequest request, HttpServletResponse response, String ip, Object message, boolean printLog) throws IOException {
        //输出警告日志
        if (printLog) {
            log.warn("请求认证失败，来访IP({})!", ip);
        }

        //输出认证响应信息
        WebUtil.write(getFailResponse(response), JsonUtil.toJson(message), Charset.UTF8);
    }

    /**
     * 设置认证响应信息
     *
     * @param response
     * @return
     */
    private static HttpServletResponse getFailResponse(HttpServletResponse response) {
        //设置状态码
        response.setStatus(AUTH_FAILURE_CODE);
        return response;
    }
}